import React, {
  useState,
  useEffect,
  useCallback,
  useRef,
  useLayoutEffect,
  useMemo,
} from "react";
import { ProjectAPI } from "@/api/project";
import { CrossingPointAPI } from "@/api/CrossingPoint";
import { ConstructionSchemeAPI } from "@/api/ConstructionScheme";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"; // 新增：Select组件

import { Badge } from "@/components/ui/badge";
import { Tooltip } from "@/components/ui/tooltip";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Plus,
  Search,
  Edit,
  Eye,
  MoreHorizontal,
  Trash2,
  RefreshCw,
  Filter,
  Building2,
  Calendar,
  User,
  ChevronLeft,
  ChevronRight, // 新增：分页箭头图标
} from "lucide-react";
import { format } from "date-fns";
import { useNavigate } from "react-router-dom";
import { createPageUrl } from "@/utils";
import { useToast } from "@/components/ui/use-toast";

import ProjectForm from "../components/projects/ProjectForm";
import ProjectFilters from "../components/projects/ProjectFilters";

// 全局样式添加
const globalStyles = `
  <style>
    /* 表格布局优化 */
    .table-container {
      table-layout: fixed;
      width: 100%;
       cursor: pointer;
    }
    
    /* 单位列样式优化 */
    .table-cell.unit-col {
      max-width: 180px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      padding: 0.75rem;
      
    }
    
    /* 其他列宽度控制 */
    .table-header-cell.project-name-col,
    .table-cell.project-name-col {
      width: 250px;
    }
    
    .table-header-cell.voltage-level-col,
    .table-cell.voltage-level-col {
      width: 100px;
    }
    
    .table-header-cell.status-col,
    .table-cell.status-col {
      width: 100px;
    }
    
    .table-header-cell.date-col,
    .table-cell.date-col {
      width: 120px;
    }
    
    .table-header-cell.manager-col,
    .table-cell.manager-col {
      width: 120px;
    }
    
    .table-header-cell.action-col,
    .table-cell.action-col {
      width: 100px;
    }

    /* 分页控件样式 */
    .pagination-container {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 1rem 1.5rem;
      border-top: 1px solid #e2e8f0;
    }
    .pagination-info {
      color: #64748b;
      font-size: 0.875rem;
    }
    .pagination-controls {
      display: flex;
      align-items: center;
      gap: 0.5rem;
    }
    .page-number-btn {
      width: 2.5rem;
      height: 2.5rem;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 0.375rem;
      border: 1px solid #e2e8f0;
      background: white;
      color: #64748b;
      cursor: pointer;
      transition: all 0.2s;
    }
    .page-number-btn:hover:not(:disabled) {
      border-color: #94a3b8;
      color: #0f172a;
    }
    .page-number-btn.active {
      background: #0f172a;
      color: white;
      border-color: #0f172a;
    }
    .page-number-btn:disabled {
      opacity: 0.5;
      cursor: not-allowed;
    }
  </style>
`;

// 注入全局样式
const styleElement = document.createElement("style");
styleElement.innerHTML = globalStyles
  .replace("<style>", "")
  .replace("</style>", "");
document.head.appendChild(styleElement);

// 状态徽章工具函数
const getStatusBadge = (status) => {
  const statusConfig = {
    notStarted: {
      color: "bg-emerald-100 text-emerald-400 border-emerald-300",
      label: "未开工",
    },
    inProgress: {
      color: "bg-blue-100 text-blue-400 border-blue-300",
      label: "已开工",
    },
    completed: {
      color: "bg-violet-100 text-violet-800 border-violet-300",
      label: "已完工",
    },
    planning: {
      // 补充缺失的planning状态
      color: "bg-amber-100 text-amber-600 border-amber-300",
      label: "规划中",
    },
  };
  const config = statusConfig[status] || statusConfig.planning;
  return (
    <Badge variant="outline" className={`${config.color} border font-medium`}>
      {config.label}
    </Badge>
  );
};

export default function Projects() {
  const formRef = useRef(null);
  const [projects, setProjects] = useState([]);
  const [filteredProjects, setFilteredProjects] = useState([]);
  const [showForm, setShowForm] = useState(false);
  const [editingProject, setEditingProject] = useState(null);
  const [searchTerm, setSearchTerm] = useState("");
  const [filters, setFilters] = useState({
    projectStatus: "all",
    voltageLevel: "all",
    unit: "",
  });
  const [isLoading, setIsLoading] = useState(true);
  const navigate = useNavigate();
  const { toast } = useToast();

  // ===== 新增：分页核心状态 =====
  const [currentPage, setCurrentPage] = useState(1); // 当前页码（默认第1页）
  const [pageSize, setPageSize] = useState(10); // 每页条数（默认10条）

  // 加载项目列表
  const loadProjects = useCallback(async () => {
    setIsLoading(true);
    let attempts = 0;
    const maxAttempts = 3;
    let delay = 1000;

    while (attempts < maxAttempts) {
      try {
        const resultProject = await ProjectAPI.getList({
          sort: "-created_date",
        });
        const fetchedProjects = resultProject.data || [];
        setProjects(Array.isArray(fetchedProjects) ? fetchedProjects : []);
        setIsLoading(false);
        setCurrentPage(1); // 重新加载数据时重置到第1页
        return;
      } catch (error) {
        attempts++;
        console.error(`加载项目失败，第 ${attempts} 次尝试:`, error);

        if (attempts >= maxAttempts) {
          toast({
            variant: "destructive",
            title: "加载项目失败",
            description:
              "多次尝试后仍无法连接到服务器。请检查您的网络连接或稍后重试。",
          });
          setIsLoading(false);
          break;
        }

        await new Promise((res) => setTimeout(res, delay));
        delay *= 2;
      }
    }
  }, [toast]);

  // 初始化加载项目
  useEffect(() => {
    loadProjects();
  }, [loadProjects]);

  // 表单滚动逻辑
  useEffect(() => {
    if (showForm && formRef.current) {
      const timer = setTimeout(() => {
        formRef.current.scrollIntoView({ behavior: "smooth", block: "center" });
      }, 200);
      return () => clearTimeout(timer);
    }
  }, [showForm]);

  // 筛选项目
  const filterProjects = useCallback(() => {
    let filtered = projects;

    if (searchTerm) {
      filtered = filtered.filter((project) =>
        project.projectName?.toLowerCase().includes(searchTerm.toLowerCase())
      );
    }

    if (filters.unit) {
      const lowerUnit = filters.unit.toLowerCase();
      filtered = filtered.filter(
        (project) =>
          project.constructionUnit?.toLowerCase().includes(lowerUnit) ||
          project.designUnit?.toLowerCase().includes(lowerUnit) ||
          project.supervisionUnit?.toLowerCase().includes(lowerUnit)
      );
    }

    if (filters.projectStatus !== "all") {
      switch (filters.projectStatus) {
        case "notStarted":
          filtered = filtered.filter(
            (p) =>
              p.projectStatus === "planning" || p.projectStatus === "notStarted"
          );
          break;
        case "inProgress":
          filtered = filtered.filter((p) => p.projectStatus === "inProgress");
          break;
        case "completed":
          filtered = filtered.filter((p) => p.projectStatus === "completed");
          break;
        default:
          break;
      }
    }

    if (filters.voltageLevel !== "all") {
      filtered = filtered.filter(
        (project) => project.voltageLevel === filters.voltageLevel
      );
    }

    setFilteredProjects(filtered);
    setCurrentPage(1); // 筛选条件变化时重置到第1页
  }, [projects, searchTerm, filters]);

  // 筛选逻辑触发
  useEffect(() => {
    filterProjects();
  }, [filterProjects]);

  // ===== 新增：分页数据计算 =====
  // 1. 总页数（向上取整，避免小数页）
  const totalPages = useMemo(() => {
    if (filteredProjects.length === 0) return 1;
    return Math.ceil(filteredProjects.length / pageSize);
  }, [filteredProjects.length, pageSize]);

  // 2. 当前页显示的数据（基于当前页码和每页条数截取）
  const paginationData = useMemo(() => {
    const startIndex = (currentPage - 1) * pageSize; // 起始索引
    const endIndex = startIndex + pageSize; // 结束索引
    return filteredProjects.slice(startIndex, endIndex); // 截取当前页数据
  }, [filteredProjects, currentPage, pageSize]);

  // ===== 新增：分页操作函数 =====
  // 上一页
  const handlePrevPage = () => {
    if (currentPage > 1) {
      setCurrentPage((prev) => prev - 1);
    }
  };

  // 下一页
  const handleNextPage = () => {
    if (currentPage < totalPages) {
      setCurrentPage((prev) => prev + 1);
    }
  };

  // 切换到指定页码
  const handlePageChange = (pageNum) => {
    // 确保页码在有效范围内（1 ~ 总页数）
    if (pageNum >= 1 && pageNum <= totalPages) {
      setCurrentPage(pageNum);
    }
  };

  // 改变每页条数（重置到第1页）
  const handlePageSizeChange = (value) => {
    setPageSize(Number(value));
    setCurrentPage(1);
  };

  // 项目提交
  const handleSubmit = async (projectData) => {
    try {
      if (editingProject) {
        await ProjectAPI.update(editingProject.id, projectData);
      } else {
        await ProjectAPI.create(projectData);
      }
      setShowForm(false);
      setEditingProject(null);
      loadProjects();
    } catch (error) {
      console.error("保存项目失败:", error);
      alert("保存项目失败: " + (error.message || "未知错误"));
    }
  };

  // 编辑项目
  const handleEdit = (project) => {
    setEditingProject(project);
    setShowForm(true);
    setTimeout(() => {
      if (formRef.current) {
        formRef.current.scrollIntoView({
          behavior: "auto",
          block: "start",
        });
      }
    }, 100);
  };

 
  const handleDeleteProject = async (projectId) => {
    if (
      window.confirm(
        "确定要删除此项目吗？此操作将同时删除所有关联的跨越点和施工方案，且无法撤销。"
      )
    ) {
      try {
        await ProjectAPI.delete(projectId);
        alert("项目及所有关联数据已成功删除。");
        loadProjects();
      } catch (error) {
        console.error("删除项目失败:", error);
        alert("删除项目失败: " + (error.message || "请稍后重试"));
      }
    }
  };

 
  const handleCancel = () => {
    setShowForm(false);
    setEditingProject(null);
  };

  return (
    <div className="min-h-screen bg-slate-50 ">
      {/* Header */}
      <div className="bg-white border-b border-slate-200">
        <div className="px-6 py-6">
          <div className="flex flex-col lg:flex-row justify-between items-start lg:items-center gap-6">
            <div>
              <h1 className="text-2xl font-bold text-slate-900 mb-2">
                项目管理
              </h1>
              <p className="text-slate-600">管理输电线路建设项目的全生命周期</p>
            </div>
            <div className="flex items-center gap-3">
              <Button
                variant="outline"
                onClick={loadProjects}
                disabled={isLoading}
              >
                <RefreshCw
                  className={`w-4 h-4 mr-2 ${isLoading ? "animate-spin" : ""}`}
                />
                刷新
              </Button>
              <Button
                onClick={() => setShowForm(true)}
                className="bg-slate-800 hover:bg-slate-900 text-white px-6"
              >
                <Plus className="w-4 h-4 mr-2" />
                新建项目
              </Button>
            </div>
          </div>
        </div>
      </div>

      {/* Filters */}
      <div className="bg-white border-b border-slate-200">
        <div className="px-6 py-4">
          <div className="flex flex-col lg:flex-row gap-4 items-center">
            <div className="relative flex-1 max-w-md">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-slate-400 w-4 h-4" />
              <Input
                placeholder="搜索项目名称..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-10 border-slate-300"
              />
            </div>
            <div className="flex items-center gap-2 text-slate-600">
              <Filter className="w-4 h-4" />
              <span className="text-sm">筛选条件</span>
            </div>
            <ProjectFilters filters={filters} onFilterChange={setFilters} />
          </div>
        </div>
      </div>

      {/* Main Content */}
      <div className="px-6 py-6">
        {/* 项目表单 */}
        {showForm && (
          <div className="mb-8" ref={formRef}>
            <ProjectForm
              project={editingProject}
              onSubmit={handleSubmit}
              onCancel={handleCancel}
            />
          </div>
        )}

        {/* 统计卡片 */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
          <div className="bg-white border border-slate-200 rounded-lg p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-slate-600">项目总数</p>
                <p className="text-2xl font-bold text-slate-900">
                  {projects.length}
                </p>
              </div>
              <Building2 className="w-8 h-8 text-slate-400" />
            </div>
          </div>
          <div className="bg-white border border-slate-200 rounded-lg p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-slate-600">未开工</p>
                <p className="text-2xl font-bold text-emerald-600">
                  {
                    projects.filter((p) => p.projectStatus === "notStarted")
                      .length
                  }
                </p>
              </div>
              <Calendar className="w-8 h-8 text-emerald-400" />
            </div>
          </div>
          <div className="bg-white border border-slate-200 rounded-lg p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-slate-600">已开工</p>
                <p className="text-2xl font-bold text-blue-600">
                  {
                    projects.filter((p) => p.projectStatus === "inProgress")
                      .length
                  }
                </p>
              </div>
              <Building2 className="w-8 h-8 text-blue-400" />
            </div>
          </div>
          <div className="bg-white border border-slate-200 rounded-lg p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-slate-600">已完成</p>
                <p className="text-2xl font-bold text-violet-600">
                  {
                    projects.filter((p) => p.projectStatus === "completed")
                      .length
                  }
                </p>
              </div>
              <User className="w-8 h-8 text-violet-800" />
            </div>
          </div>
        </div>

        {/* Projects Table + 分页控件 */}
        <div className="bg-white border border-slate-200 rounded-lg shadow-sm ">
          {/* 横向滚动容器（适配小屏幕） */}
          <div className="overflow-x-auto ">
            <Table className="table-container ">
              <TableHeader className="bg-slate-50">
                <TableRow className="border-slate-200">
                  <TableHead className="text-slate-700 font-semibold table-header-cell project-name-col p-2">
                    项目名称
                  </TableHead>
                  <TableHead className="text-slate-700 font-semibold table-header-cell voltage-level-col">
                    电压等级
                  </TableHead>
                  <TableHead className="text-slate-700 font-semibold table-header-cell status-col">
                    项目状态
                  </TableHead>
                  <TableHead className="text-slate-700 font-semibold table-header-cell date-col">
                    开工时间
                  </TableHead>
                  <TableHead className="text-slate-700 font-semibold table-header-cell date-col">
                    完工时间
                  </TableHead>
                  <TableHead className="text-slate-700 font-semibold table-header-cell manager-col">
                    项目经理
                  </TableHead>
                  <TableHead className="text-slate-700 font-semibold table-header-cell unit-col">
                    施工单位
                  </TableHead>
                  <TableHead className="text-slate-700 font-semibold table-header-cell unit-col">
                    设计单位
                  </TableHead>
                  <TableHead className="text-slate-700 font-semibold table-header-cell unit-col">
                    监理单位
                  </TableHead>
                  <TableHead className="text-slate-700 font-semibold table-header-cell action-col text-right">
                    操作
                  </TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {isLoading ? (
                  Array(5)
                    .fill(0)
                    .map((_, i) => (
                      <TableRow key={i} className="border-slate-200">
                        <TableCell colSpan={10} className="text-center py-8">
                          <div className="animate-pulse flex justify-center items-center">
                            <div className="h-4 bg-slate-200 rounded w-32"></div>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))
                ) : filteredProjects.length === 0 ? (
                  <TableRow className="border-slate-200">
                    <TableCell
                      colSpan={10}
                      className="text-center py-12 text-slate-500"
                    >
                      <Building2 className="w-12 h-12 mx-auto mb-4 text-slate-300" />
                      <h3 className="text-lg font-medium text-slate-600 mb-2">
                        未找到项目
                      </h3>
                      <p>请尝试调整筛选条件或创建新项目。</p>
                    </TableCell>
                  </TableRow>
                ) : (
                  paginationData.map((project) => (
                    <TableRow
                      key={project.id}
                      className="border-slate-200 hover:bg-slate-50 transition-colors"
                    >
                      <TableCell
                        className="table-cell project-name-col font-medium text-slate-700"
                        onClick={() =>
                          navigate(
                            createPageUrl(`ProjectDetail?id=${project.id}`)
                          )
                        }
                      >
                        {project.projectName}
                      </TableCell>
                      <TableCell className="table-cell voltage-level-col">
                        <Badge
                          variant="outline"
                          className="bg-slate-100 text-slate-700 border-slate-300"
                        >
                          {project.voltageLevel || "-"}
                        </Badge>
                      </TableCell>
                      <TableCell className="table-cell status-col  text-slate-600 ">
                        {getStatusBadge(project.projectStatus)}
                      </TableCell>
                      <TableCell className="table-cell date-col text-slate-600">
                        {project.plannedStartDate
                          ? format(
                              new Date(project.plannedStartDate),
                              "yyyy-MM-dd"
                            )
                          : "-"}
                      </TableCell>
                      <TableCell className="table-cell date-col text-slate-600">
                        {project.plannedEndDate
                          ? format(
                              new Date(project.plannedEndDate),
                              "yyyy-MM-dd"
                            )
                          : "-"}
                      </TableCell>
                      <TableCell className="table-cell manager-col text-slate-600">
                        {project.projectManager || "-"}
                      </TableCell>
                      <TableCell
                        className="table-cell unit-col text-slate-600"
                        title={project.constructionUnit || "-"}
                      >
                        <Tooltip content={project.constructionUnit}>
                          {project.constructionUnit || "-"}
                        </Tooltip>
                      </TableCell>
                      <TableCell
                        className="table-cell unit-col text-slate-600"
                        title={project.designUnit || "-"}
                      >
                        <Tooltip content={project.designUnit}>
                          {project.designUnit || "-"}
                        </Tooltip>
                      </TableCell>
                      <TableCell
                        className="table-cell unit-col text-slate-600"
                        title={project.supervisionUnit || "-"}
                      >
                        <Tooltip content={project.supervisionUnit}>
                          {project.supervisionUnit || "-"}
                        </Tooltip>
                      </TableCell>
                      <TableCell className="table-cell action-col text-right">
                        <DropdownMenu>
                          <DropdownMenuTrigger asChild>
                            <Button
                              variant="ghost"
                              size="icon"
                              className="text-slate-400 hover:text-slate-600"
                            >
                              <MoreHorizontal className="w-4 h-4" />
                            </Button>
                          </DropdownMenuTrigger>
                          <DropdownMenuContent
                            align="end"
                            className="bg-white border border-slate-200"
                          >
                            <DropdownMenuItem
                              onClick={() =>
                                navigate(
                                  createPageUrl(
                                    `ProjectDetail?id=${project.id}`
                                  )
                                )
                              }
                              className="hover:bg-slate-50"
                            >
                              <Eye className="w-4 h-4 mr-2" />
                              查看详情
                            </DropdownMenuItem>
                            <DropdownMenuItem
                              onClick={() => handleEdit(project)}
                              className="hover:bg-slate-50"
                            >
                              <Edit className="w-4 h-4 mr-2" />
                              编辑
                            </DropdownMenuItem>
                            <DropdownMenuItem
                              onClick={() => handleDeleteProject(project.id)}
                              className="hover:bg-slate-50 text-red-600"
                            >
                              <Trash2 className="w-4 h-4 mr-2" />
                              删除
                            </DropdownMenuItem>
                          </DropdownMenuContent>
                        </DropdownMenu>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>

          {/* ===== 新增：分页控件 UI ===== */}
          {!isLoading && filteredProjects.length > 0 && (
            <div className="pagination-container">
              {/* 分页信息（显示总条数、当前页范围） */}
              <div className="pagination-info">
                共 {filteredProjects.length} 条数据 · 显示第{" "}
                {(currentPage - 1) * pageSize + 1} 至{" "}
                {Math.min(currentPage * pageSize, filteredProjects.length)} 条
              </div>

              {/* 分页控制（每页条数选择 + 页码切换） */}
              <div className="pagination-controls">
                {/* 每页条数选择 */}
                <Select
                  value={pageSize.toString()}
                  onValueChange={handlePageSizeChange}
                >
                  <SelectTrigger className="w-[80px] h-8 text-sm">
                    <SelectValue placeholder="每页条数" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="5">5条/页</SelectItem>
                    <SelectItem value="10">10条/页</SelectItem>
                    <SelectItem value="20">20条/页</SelectItem>
                    <SelectItem value="50">50条/页</SelectItem>
                  </SelectContent>
                </Select>

                {/* 上一页按钮 */}
                <button
                  className="page-number-btn"
                  onClick={handlePrevPage}
                  disabled={currentPage === 1}
                >
                  <ChevronLeft className="w-4 h-4" />
                </button>

                {/* 页码按钮组（最多显示5个页码，避免过多） */}
                {Array.from({ length: totalPages }, (_, i) => i + 1).map(
                  (page) => {
                    // 只显示当前页前后2页 + 首页/末页（优化大屏体验）
                    if (
                      page === 1 ||
                      page === totalPages ||
                      (page >= currentPage - 2 && page <= currentPage + 2)
                    ) {
                      return (
                        <button
                          key={page}
                          className={`page-number-btn ${
                            currentPage === page ? "active" : ""
                          }`}
                          onClick={() => handlePageChange(page)}
                        >
                          {page}
                        </button>
                      );
                    }
                    // 中间省略号（当页码超过5个时显示）
                    if (
                      (page === currentPage - 3 && totalPages > 5) ||
                      (page === currentPage + 3 && totalPages > 5)
                    ) {
                      return (
                        <span
                          key={`ellipsis-${page}`}
                          className="text-slate-400"
                        >
                          ...
                        </span>
                      );
                    }
                    return null;
                  }
                )}

                {/* 下一页按钮 */}
                <button
                  className="page-number-btn"
                  onClick={handleNextPage}
                  disabled={currentPage === totalPages}
                >
                  <ChevronRight className="w-4 h-4" />
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
